package com.jxwifi.cloud.quickclean.assemble;

import android.content.Context;
import android.graphics.Paint;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.idroid.utils.NoDoubleClickListener;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.AssemRecordsBean;
import com.jxwifi.cloud.quickclean.bean.AssembleItemsBean;
import com.jxwifi.cloud.quickclean.bean.PayParamsBean;
import com.jxwifi.cloud.quickclean.bean.StrListBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.pay.PayUtil;
import com.jxwifi.cloud.quickclean.popwindow.PopPayDepositModule;
import com.jxwifi.cloud.quickclean.utils.KAlertDialog;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.jxwifi.cloud.quickclean.utils.TokenTimeUtils;
import com.jxwifi.cloud.quickclean.utils.shareUtils;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import retrofit2.http.PUT;

public class ADetailsPresenter {

    private String TAG = this.getClass().getSimpleName();
    private static final String StrUrlDefult = "https://kjb-oss.oss-cn-shenzhen.aliyuncs.com/ul9zg740a645wxjfxddl.png";

    private Context mContext;

    private ADetailsView mView;

    private AuzImpl mAuz;

    private CountDownTimer timer;

    private long seconds;

    private AssembleItemsBean mBean;

    private String mStrorder;

    private AssemRecordsBean mRecordBean;

    private boolean isRefreshFlag = false;

    private String PeopleName = "";

    private PayParamsBean mPayPrepay;

    public ADetailsPresenter(Context context, ADetailsView view) {
        this.mContext = context;
        this.mView = view;
        this.mAuz = new AuzImpl();
    }

    public void initDatailsData(){
        Params params=new Params();
        params.add("orderCode",mView.getDetailsBean().getOrderCode());
        mAuz.auzget(UrlPool.GET_COLLAGE_RECORD_INFO, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                mRecordBean=JSON.parseObject(data, AssemRecordsBean.class);
                //Log.i(TAG,"initDatailsData mRecordBean ==> orderCode = "+mRecordBean.getOrderCode());
               //Log.i(TAG,"initDatailsData mRecordBean ==> data = "+data);
                initView();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void initView() {
        if (!TextUtils.isEmpty(mRecordBean.getProductImage())) {
            Glide.with(mContext).load(mRecordBean.getProductImage()).into(mView.getDetailsImages());
        } else {
            Glide.with(mContext).load(StrUrlDefult).into(mView.getDetailsImages());
        }
        mView.getDetailsName().setText(mRecordBean.getProductName());
        mView.getOriginalPrice().getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        mView.getDescription().getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        mView.getAllNumber().setText("拼单总人数:" + mRecordBean.getPsum());
        mView.getStartsTime().setText("拼单时间"+mRecordBean.getCollageRecordCreateTime());
        //Log.i(TAG,"initView ==> isCollage = "+mRecordBean.isCollage());
        if (mRecordBean.isCollage()) {
            mView.getOrTrue().setText("是否成团:已成团");
            mView.getAssembleTime().setText("拼单剩余时间:00:00");
        } else {
            if(isRefreshFlag){
                mView.getDetailsCancel().setVisibility(View.VISIBLE);
                shareDialog();
                isRefreshFlag = false;
            }
            mView.getOrTrue().setText("是否成团:未成团");
            try {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date curDate = new Date(System.currentTimeMillis());
                Date endDate = formatter.parse(mRecordBean.getSurplusTime());
                seconds = endDate.getTime() - curDate.getTime();
                if (seconds > 0) {
                    setTimerCount(seconds);
                } else {
                    mView.getAssembleTime().setText("拼单剩余时间:00:00:00");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (seconds > 0) {
                mView.getDetaislOver().setVisibility(View.GONE);
                mView.getDetailsSharIt().setVisibility(View.VISIBLE);
            } else {
                mView.getDetaislOver().setVisibility(View.VISIBLE);
                mView.getDetailsSharIt().setVisibility(View.GONE);
            }
        }

        mView.getNumbering().setText("拼单编号" + mRecordBean.getCdesk());
        mView.getDifference().setText("相差人数:" + mRecordBean.getDistanceNumber()+"人");
        joinPersonner();
        initData();
        //DecimalFormat df = new DecimalFormat("#0.00");
        //discountPrice = df.format(mRecordBean.getPrice()*Double.parseDouble(mRecordBean.getSubDiscountValue().split("\\.")[0])/100);

    }

    public void joinPersonner() {
        Params params = new Params();
        params.add("cdesk", mView.getDetailsBean().getCdesk());
        mAuz.auzget(UrlPool.GET_JOIN_PERSONNER, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                List<AssemRecordsBean> mListBean = JSON.parseArray(data, AssemRecordsBean.class);
                //Log.i(TAG,"joinPersonner() ==> data = "+data);
                if (mListBean.size() > 0) {
                    for (int i = 0; i < mListBean.size(); i++) {
                        if (i == 0) {
                            PeopleName = mListBean.get(i).getNickname();
                        } else {
                            PeopleName = PeopleName + ";" + mListBean.get(i).getNickname();
                        }
                    }
                }
                mView.getAssemblePeople().setText("拼单人:"+PeopleName);
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void initData(){
        Params params=new Params();
        params.add("joinType","join");
        params.add("optionCode",mRecordBean.getCno());
        params.add("optionType",mRecordBean.getCtype());
        params.add("serviceCode",mRecordBean.getServiceCode());
        mAuz.auzpost(UrlPool.ASSEMBLE_DETAILS, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                mBean= JSON.parseObject(data, AssembleItemsBean.class);
                //Log.i(TAG,"initData mBean ==> data = "+data);
                PhotoUrl();
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void PhotoUrl() {
        if (!TextUtils.isEmpty(mBean.getSpecs())){
            mView.getSpecification().setVisibility(View.VISIBLE);
            List<StrListBean> mList = new ArrayList<>();
            mList = JSON.parseArray(mBean.getSpecs(), StrListBean.class);
            String Specifications = "";
            for (int i = 0; i < mList.size(); i++) {
                if (i==0){
                    Specifications=mList.get(i).getKey()+"    "+mList.get(i).getValue();
                }else{
                    Specifications=Specifications+"\n"+mList.get(i).getKey()+"    "+mList.get(i).getValue();
                }
            }
            mView.getSpecification().setText(Specifications);
        }else{
            mView.getSpecification().setVisibility(View.GONE);
        }
        //Log.i(TAG,"PhotoUrl ==> getOrderType = "+mView.getOrderType());
        if ("join".equals(mView.getOrderType())){
            mView.getDetaislOver().setVisibility(View.GONE);
            mView.getDetailsSharIt().setVisibility(View.GONE);
            mView.getDetailsCancel().setVisibility(View.GONE);
            mView.getDetailsButton().setVisibility(View.VISIBLE);


            mView.getDetailsButton().setText("\u00A5"+mBean.getDiscountPrice()+"\n"+"立即加入");
        }else{
            mView.getDetailsButton().setVisibility(View.GONE);
            if (mRecordBean.isCollage()) {
                mView.getDetaislOver().setVisibility(View.VISIBLE);
                mView.getDetailsSharIt().setVisibility(View.GONE);
                mView.getDetailsCancel().setVisibility(View.GONE);
            }else{
                if (seconds > 0 && !"refund".equals(mRecordBean.getCollageRecord().getOrderState())) {

                        mView.getDetaislOver().setVisibility(View.GONE);
                        mView.getDetailsSharIt().setVisibility(View.VISIBLE);
                        mView.getDetailsCancel().setText("取消拼团");
                        mView.getDetailsCancel().setClickable(true);

                   /* if ("paid".equals(mRecordBean.getCollageRecord().getOrderState())){
                        mView.getDetaislOver().setVisibility(View.GONE);
                        mView.getDetailsSharIt().setVisibility(View.VISIBLE);
                        mView.getDetailsCancel().setText("已付款");
                        mView.getDetailsCancel().setClickable(false);
                    }else{
                        mView.getDetaislOver().setVisibility(View.GONE);
                        mView.getDetailsSharIt().setVisibility(View.VISIBLE);
                        mView.getDetailsCancel().setText("取消拼团");
                        mView.getDetailsCancel().setClickable(true);
                    }*/
                }else{
                    if ("refund".equals(mRecordBean.getCollageRecord().getOrderState())){
                        mView.getDetailsCancel().setVisibility(View.VISIBLE);
                        mView.getDetailsCancel().setText("已退款");
                        mView.getDetailsCancel().setClickable(false);
                        mView.getDetaislOver().setVisibility(View.GONE);
                        mView.getDetailsSharIt().setVisibility(View.GONE);
                        mView.getDetailsButton().setVisibility(View.GONE);
                    }else{
                        mView.getDetaislOver().setVisibility(View.VISIBLE);
                        mView.getDetailsSharIt().setVisibility(View.GONE);
                    }
                }
            }
        }
        mView.getDetailsPrice().setText("" + mBean.getDiscountPrice());
        mView.getOriginalPrice().setText("原价\u00A5" + mRecordBean.getPrice());

        mView.getDetailsGiveAway().setText(mBean.getAdditionalName()+""+mBean.getAdditionalValue());
        if (!TextUtils.isEmpty(mBean.getIntroduce())){
            mView.getWebViewShow().setVisibility(View.VISIBLE);
            mView.getWebViewShow().getSettings().setLoadWithOverviewMode(true);
            mView.getWebViewShow().getSettings().setDefaultTextEncodingName("UTF-8");
            StringBuilder sb = new StringBuilder();
            sb.append("<link rel=\"stylesheet\" href=\"file:///android_asset/common.css\" type=\"text/css\"/> ");
            sb.append("<div class=\"touch-detail\">");
            sb.append(mBean.getIntroduce());
            sb.append("</div>");

            mView.getWebViewShow().loadDataWithBaseURL("about:blank", sb.toString(), "text/html", "utf-8", null);
        }else{
            mView.getWebViewShow().setVisibility(View.GONE);
        }
    }

    public void assembleCancel(){
        Params params=new Params();
        //Log.i(TAG,"assembleCancel ==> getOrderType = "+mView.getOrderType());
        if(mPayPrepay == null){
            params.add("orderCode",mRecordBean.getOrderCode());
        }else{
            params.add("orderCode",mPayPrepay.getOutTradNo());
        }
        //Log.i(TAG,"assembleCancel ==> orderCode = "+mRecordBean.getOrderCode()+" OutTradNo = "+mPayPrepay.getOutTradNo());
        mAuz.auzpost(UrlPool.POST_CANCEL, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code==0){
                    mView.onCancelSuccess();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    //支付弹框
    public void paySetMeal(){
        PopPayDepositModule mPopPayOrder = new PopPayDepositModule(mContext, mBean.getDiscountPrice(), "支付金额", new PopPayDepositModule.PopPayListener() {
            @Override
            public void getPayOrder(String PayType, String PayPrice) {
                initJoin(PayType);
            }
        });
        Popwindows window = PopWindowUtil.getPopupWindow(mPopPayOrder.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.MATCH_PARENT);
        mPopPayOrder.setPopwindow(window);
        window.show(mView.getDescription(), Popwindows.Location.TOP);
    }

    public void initJoin(String PayPrice){
        Params params=new Params();
        params.add("cdesk",mRecordBean.getCdesk());
        params.add("cno",mRecordBean.getCno());
        params.add("optionType",mBean.getOptionType());
        params.add("payChannelEnum",PayPrice);
        params.add("serviceCode",mBean.getServiceCode());
        params.add("tradeType","APP");
        mAuz.auzpost(UrlPool.POST_JOIN, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                JSONObject obj = JSON.parseObject(data);
                String str = obj.getString("payPrepay");
                mStrorder = obj.getString("collageRecord");
                //Log.i(TAG,"initJoin ==> data = "+data);
                mPayPrepay = JSON.parseObject(str, PayParamsBean.class);
                if (StateUtils.PAY_ALI.equals(mPayPrepay.getPayChannelEnum())) { //支付宝
                    PayUtil.getInstance().aliPay(mContext, mPayPrepay);
                } else if (StateUtils.PAY_WX.equals(mPayPrepay.getPayChannelEnum())) { //微信
                    //mView.getWXPayCode(mASBean.getPayPrepay().getOutTradNo());
                    PayUtil.getInstance().WXPay(mContext, mPayPrepay.getWxPayResult());
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                //Log.i(TAG,"initJoin ==> msg = "+msg);
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void RefreshView(){
        //AssemRecordsBean mnewBean = JSON.parseObject(mStrorder, AssemRecordsBean.class);
        //mView.setDetailsBean(mnewBean);
        mView.setOrderType("start");
        //initView();
        initDatailsData();
        //Log.i(TAG,"RefreshView ==> isCollage = "+mRecordBean.isCollage());
        isRefreshFlag = true;
        
    }

    //倒计时操作
    private void setTimerCount(long surplusTime) {
        timer = new CountDownTimer(surplusTime, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mView.getAssembleTime().setText("拼单剩余时间:" + TokenTimeUtils.getSecondToDayHourMinutes(millisUntilFinished));
            }

            @Override
            public void onFinish() {
                timer.cancel();
                mView.getAssembleTime().setText("拼单剩余时间:0天00:00");
            }
        };
        timer.start();
    }

    public void weChatShare(IWXAPI iwxapi, int flag, Context mContext){

        shareUtils.share2weixin(iwxapi,flag ,mContext,6,mRecordBean.getOrderCode(),mRecordBean.getCdesk());
    }

    private void shareDialog(){
        final KAlertDialog dialogshow=new KAlertDialog(mContext,"邀请好友加入拼团");
        dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {

                IWXAPI mIWXAPI = WXAPIFactory.createWXAPI(mContext, StateUtils.WX_APPID, false);
                mIWXAPI.registerApp(StateUtils.WX_APPID);
                weChatShare(mIWXAPI, 1, mContext);
                dialogshow.dismiss();
            }
        });
        dialogshow.show();
    }

    public String getPeopleName() {
        return PeopleName;
    }
}
